﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace VGSoftware.AutoExtractService
{
	public class RarProcesser
	{
		public static void ProcessDirectory(DirectoryInfo directory)
		{
			try
			{
				ProcessDirectory(directory, directory, Guid.NewGuid());
			}
			catch { }
		}

		private static void ProcessDirectory(DirectoryInfo directory, DirectoryInfo rootDirectory, Guid transactionId)
		{
			foreach (DirectoryInfo subFolder in directory.GetDirectories())
			{
				if (!Settings.Exclude.Any(folder => subFolder.Name.CompareStrings(folder, true)))
				{
					ProcessDirectory(subFolder, rootDirectory, transactionId);
				}
			}
			string extract = System.IO.Path.Combine(directory.FullName, "*.*");
			string extractTo = System.IO.Path.Combine(Properties.Settings.Default.PathToExtractTo, directory.FullName.Substring(rootDirectory.Parent.FullName.Length + 1));
			extractTo += Path.DirectorySeparatorChar;

			PlugIn.Data data = new PlugIn.Data();
			data.TransactionId = transactionId;
			data.SourceRootDirectory = rootDirectory;
			data.SourceDirectory = directory;
			data.TargetDirectory = new DirectoryInfo(extractTo);

			if (PlugIn.PlugInManager.Instance.BeforeFilesExtracted(data))
			{
				Process process = new Process();
				process.StartInfo.FileName = Properties.Settings.Default.WinRarPath;
				process.StartInfo.Arguments = string.Format("x -y \"{0}\" \"{1}\"", extract, extractTo);
				process.StartInfo.CreateNoWindow = true;
				process.Start();
				process.WaitForExit();

				PlugIn.PlugInManager.Instance.AfterFilesExtracted(data);
			}
		}
	}
}
